{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c2c4268c",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# 自定义层\n",
    "\n",
    "深度学习成功背后的一个因素是神经网络的灵活性：\n",
    "我们可以用创造性的方式组合不同的层，从而设计出适用于各种任务的架构。\n",
    "例如，研究人员发明了专门用于处理图像、文本、序列数据和执行动态规划的层。\n",
    "有时我们会遇到或要自己发明一个现在在深度学习框架中还不存在的层。\n",
    "在这些情况下，必须构建自定义层。本节将展示如何构建自定义层。\n",
    "\n",
    "## 不带参数的层\n",
    "\n",
    "首先，我们(**构造一个没有任何参数的自定义层**)。\n",
    "回忆一下在 :numref:`sec_model_construction`对块的介绍，\n",
    "这应该看起来很眼熟。\n",
    "下面的`CenteredLayer`类要从其输入中减去均值。\n",
    "要构建它，我们只需继承基础层类并实现前向传播功能。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dcccedea",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:42.700516Z",
     "iopub.status.busy": "2022-12-07T17:00:42.700056Z",
     "iopub.status.idle": "2022-12-07T17:00:43.838393Z",
     "shell.execute_reply": "2022-12-07T17:00:43.837505Z"
    },
    "origin_pos": 2,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "from torch import nn\n",
    "\n",
    "\n",
    "class CenteredLayer(nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "\n",
    "    def forward(self, X):\n",
    "        return X - X.mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bad6f33",
   "metadata": {
    "origin_pos": 5
   },
   "source": [
    "让我们向该层提供一些数据，验证它是否能按预期工作。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "4b4d1d06",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.842407Z",
     "iopub.status.busy": "2022-12-07T17:00:43.841864Z",
     "iopub.status.idle": "2022-12-07T17:00:43.856009Z",
     "shell.execute_reply": "2022-12-07T17:00:43.855164Z"
    },
    "origin_pos": 7,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([-2., -1.,  0.,  1.,  2.])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "layer = CenteredLayer()\n",
    "layer(torch.FloatTensor([1, 2, 3, 4, 5]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f5c194e",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "现在，我们可以[**将层作为组件合并到更复杂的模型中**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "940a1768",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.859555Z",
     "iopub.status.busy": "2022-12-07T17:00:43.859007Z",
     "iopub.status.idle": "2022-12-07T17:00:43.864905Z",
     "shell.execute_reply": "2022-12-07T17:00:43.864115Z"
    },
    "origin_pos": 12,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "net = nn.Sequential(nn.Linear(8, 128), CenteredLayer())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e3ed550",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "作为额外的健全性检查，我们可以在向该网络发送随机数据后，检查均值是否为0。\n",
    "由于我们处理的是浮点数，因为存储精度的原因，我们仍然可能会看到一个非常小的非零数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "235e88c8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.868175Z",
     "iopub.status.busy": "2022-12-07T17:00:43.867649Z",
     "iopub.status.idle": "2022-12-07T17:00:43.873777Z",
     "shell.execute_reply": "2022-12-07T17:00:43.873018Z"
    },
    "origin_pos": 16,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(-1.3970e-09, grad_fn=<MeanBackward0>)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Y = net(torch.rand(4, 8))\n",
    "Y.mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "406e792f",
   "metadata": {
    "origin_pos": 19
   },
   "source": [
    "## [**带参数的层**]\n",
    "\n",
    "以上我们知道了如何定义简单的层，下面我们继续定义具有参数的层，\n",
    "这些参数可以通过训练进行调整。\n",
    "我们可以使用内置函数来创建参数，这些函数提供一些基本的管理功能。\n",
    "比如管理访问、初始化、共享、保存和加载模型参数。\n",
    "这样做的好处之一是：我们不需要为每个自定义层编写自定义的序列化程序。\n",
    "\n",
    "现在，让我们实现自定义版本的全连接层。\n",
    "回想一下，该层需要两个参数，一个用于表示权重，另一个用于表示偏置项。\n",
    "在此实现中，我们使用修正线性单元作为激活函数。\n",
    "该层需要输入参数：`in_units`和`units`，分别表示输入数和输出数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7daf5257",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.877216Z",
     "iopub.status.busy": "2022-12-07T17:00:43.876666Z",
     "iopub.status.idle": "2022-12-07T17:00:43.881991Z",
     "shell.execute_reply": "2022-12-07T17:00:43.881201Z"
    },
    "origin_pos": 21,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [],
   "source": [
    "class MyLinear(nn.Module):\n",
    "    def __init__(self, in_units, units):\n",
    "        super().__init__()\n",
    "        self.weight = nn.Parameter(torch.randn(in_units, units))\n",
    "        self.bias = nn.Parameter(torch.randn(units,))\n",
    "    def forward(self, X):\n",
    "        linear = torch.matmul(X, self.weight.data) + self.bias.data\n",
    "        return F.relu(linear)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fefaab88",
   "metadata": {
    "origin_pos": 25,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "接下来，我们实例化`MyLinear`类并访问其模型参数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f698e334",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.885384Z",
     "iopub.status.busy": "2022-12-07T17:00:43.884832Z",
     "iopub.status.idle": "2022-12-07T17:00:43.891052Z",
     "shell.execute_reply": "2022-12-07T17:00:43.890262Z"
    },
    "origin_pos": 28,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Parameter containing:\n",
       "tensor([[ 1.9094, -0.8244, -1.6846],\n",
       "        [ 0.6850,  0.8366, -1.3837],\n",
       "        [ 0.0289,  2.0976,  1.3855],\n",
       "        [-0.8574, -0.3557, -0.4109],\n",
       "        [ 2.2963, -1.3008,  1.2173]], requires_grad=True)"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "linear = MyLinear(5, 3)\n",
    "linear.weight"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b3e70bb",
   "metadata": {
    "origin_pos": 30
   },
   "source": [
    "我们可以[**使用自定义层直接执行前向传播计算**]。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "73bdadeb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.894343Z",
     "iopub.status.busy": "2022-12-07T17:00:43.893790Z",
     "iopub.status.idle": "2022-12-07T17:00:43.899843Z",
     "shell.execute_reply": "2022-12-07T17:00:43.899055Z"
    },
    "origin_pos": 32,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0.0984, 0.5687, 2.8316],\n",
       "        [2.2558, 0.0000, 1.8880]])"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "linear(torch.rand(2, 5))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08e9b68f",
   "metadata": {
    "origin_pos": 35
   },
   "source": [
    "我们还可以(**使用自定义层构建模型**)，就像使用内置的全连接层一样使用自定义层。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "062d9c7b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2022-12-07T17:00:43.903259Z",
     "iopub.status.busy": "2022-12-07T17:00:43.902701Z",
     "iopub.status.idle": "2022-12-07T17:00:43.909376Z",
     "shell.execute_reply": "2022-12-07T17:00:43.908630Z"
    },
    "origin_pos": 37,
    "tab": [
     "pytorch"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[7.5465],\n",
       "        [4.6817]])"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = nn.Sequential(MyLinear(64, 8), MyLinear(8, 1))\n",
    "net(torch.rand(2, 64))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b798a9f4",
   "metadata": {
    "origin_pos": 40
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 我们可以通过基本层类设计自定义层。这允许我们定义灵活的新层，其行为与深度学习框架中的任何现有层不同。\n",
    "* 在自定义层定义完成后，我们就可以在任意环境和网络架构中调用该自定义层。\n",
    "* 层可以有局部参数，这些参数可以通过内置函数创建。\n",
    "\n",
    "## 练习\n",
    "\n",
    "1. 设计一个接受输入并计算张量降维的层，它返回$y_k = \\sum_{i, j} W_{ijk} x_i x_j$。\n",
    "1. 设计一个返回输入数据的傅立叶系数前半部分的层。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0da253c7",
   "metadata": {
    "origin_pos": 42,
    "tab": [
     "pytorch"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/1835)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}